import React from "react";
import { Button, Card, Table, Modal, Form, Input, Upload, message } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import { getTrademarkList, addOrUpdateTrademark, remove } from "@api/product";
import type {
  TrademarkData,
  TrademarkListData,
} from "@api/product/model/productData";
import { useEffect, useState } from "react";
import type { ColumnsType } from "antd/lib/table";
import "./index.less";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";

export default function Trademark() {

  // 定义数据
  const [trademarkList, setTrademarkList] = useState<TrademarkListData>([]);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [total, setTotal] = useState(0);
  const [open, setOpen] = useState(false);
  // 通过Form.useForm获取到表单数据
  const [form] = Form.useForm();
  // 上传图片数据
  const [loading, setLoading] = useState(false);
  const [imgUrl, setLogoUrl] = useState<string>("");

  const [RowId, setRowId] = useState<string>();


  // 获取品牌列表展示数据 -- 表格展示数据
  const TrademarkList = async (page: number, limit: number) => {
    try {
      const result = await getTrademarkList(page, limit);
      setCurrent(result.current);
      setPageSize(result.size);
      setTotal(result.total);
      setTrademarkList(result.records);
    } catch (error) {
      return Promise.reject(error);
    }
  };

  //对表单数据域进行交互，提交表单 --整理数据、发请求
  const onFinish = async (values: any) => {
    let tmFrom = {
      id: RowId ? RowId : undefined,
      tmName: values.tmName,
      logoUrl: imgUrl
    }
    try {
      await addOrUpdateTrademark(tmFrom);
      TrademarkList(current, pageSize);
    } catch (error) {
      return Promise.reject(error);
    }
  };

  // 点击Modal确定按钮
  const addNewTrademark = () => {
    form
      .validateFields()
      .then((values) => {
        onFinish(values);
        setOpen(false);
        form.resetFields();
        if (RowId) {
          message.success("更新成功");
        } else {
          message.success("添加成功");
        }
      })
      .catch((errorInfo) => {
        // debugger //打断点用的，查错误
        message.error(errorInfo.errorFields);
        // 直接就是返回的失败的Promise，不需要再自己返回；
      });
  };

  // 点击操作的修改按钮，要数据回显--数据回显就需要用拷贝
  const updateTrademark = (row: TrademarkData) => {
    setOpen(true);
    // 这里是为了在数据回显后，把返回来的id保存一下，方便后续发请求改的是哪个数据
    // 在提交表单时，发请求需要传参数；因为修改和添加传的都是对象，对象中包含id
    setRowId(row.id as string);
    // console.log(row)
    // 浅拷贝，不然会报错
    const Row = { ...row };
    // setTrademarkInfo(Row)
    // 把返回来的图片地址保存一下，一是点击对话框后，显示出来的图片是自己定义的数据，
    // 但表单中的数据是需要自己手动调用api函数添加的
    setLogoUrl(Row.logoUrl);
    form.setFieldsValue({
      tmName: Row.tmName,
      logoUrl: Row.logoUrl
    });
  };

  // 点击操作删除按钮，重新发请求
  const deleteTrademark = async (row: TrademarkData) => {
    try {
      await remove(row.id as number);
      TrademarkList(current, pageSize);
    } catch (error) {
      return Promise.reject(error);
    }
  };

  
  // 点击添加，显示对话框,清空表单的数据和自己定义的数据
  const showAddModal = () => {
    setOpen(true);
    form.resetFields();
    setLogoUrl("");
    setRowId("");
  };

  // 点击取消对话框
  const cancelModal = () => {
    setOpen(false);
    form.resetFields();
    setLogoUrl("");
    setRowId('');
  };

  // 声明周期--挂载显示数据发请求
  useEffect(() => {
    TrademarkList(current, pageSize);
  }, []);

 
  // 图片上传前的校验
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("必须上传品牌图片");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("上传的图片必须是jpg且不能大于2M");
    }
    return isJpgOrPng && isLt2M;
  };
  // 图片改变触发事件，info图片列表的信息
  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      setLogoUrl(info.file.response.data)
    }
  };
  // 上传图片的显示按钮
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传品牌LOGO</div>
    </div>
  );


  // 表格结构数据
  const columns: ColumnsType<TrademarkData> = [
    
    {
      title: "序号",
      render: (row, records, index) => index + 1,
      align: "center",
      width: 80,
    },
    {
      title: "品牌名称",
      dataIndex: "tmName",
      width:200
    },
    {
      title: "品牌LOGO",
      render: (row) => (
        <img alt="" className="trademark-logo" src={row.logoUrl} />
      ),
    },
    {
      title: "操作",
      width: 250,
      render: (row) => {
        return (
          <>
            <Button
              type="primary"
              className="change"
              icon={<EditOutlined />}
              onClick={() => updateTrademark(row)}
            >
              修改
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => deleteTrademark(row)}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];



  return (
    <>
      <Card bordered>
        <Button
          onClick={showAddModal}
          type="primary"
          size="large"
          icon={<PlusOutlined style={{ color: "white" }} />}
        >
          添加
        </Button>
      </Card>
      <Modal
        title="添加或修改品牌"
        visible={open}
        okText="确认"
        cancelText="取消"
        onOk={addNewTrademark}
        onCancel={cancelModal}
        // forceRender
        // closable={false}
        centered
      >
        <Form
          form={form}
          onFinish={onFinish}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          layout="horizontal"
          // onValuesChange={onValuesChange}
          // disabled={componentDisabled}
        >
          <Form.Item
            name="tmName"
            label="品牌名称"
            rules={[{ required: true, message: "品牌名称必须填写" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            valuePropName="logoUrl"
            name="logoUrl"
            label="品牌LOGO"
            rules={[{ required: true, message: "品牌LOGO必须上传" }]}
          >
            <Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/app-dev/admin/product/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imgUrl ? (
                <img src={imgUrl} alt="avatar" style={{ width: "100%" }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Card bordered>
        <Table
          columns={columns}
          dataSource={trademarkList}
          bordered
          rowKey="id"
          pagination={{
            current,
            pageSize,
            total,
            pageSizeOptions: [5, 10],
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `总共：${total}`,
            // 页码或 pageSize 改变的回调
            onChange: (current, pageSize) => {
              // 发送请求，请求新的数据
              TrademarkList(current, pageSize);
            },
          }}
        />
      </Card>
    </>
  );
}
